﻿#if ODIN_INSPECTOR
using Sirenix.OdinInspector;
#endif
using System;
using System.Linq;
using UnityEngine;

namespace JH
{
    /// <summary>
    ///  竖线和曲线的交点类
    /// </summary>
    public class IntersectionPoint : MonoBehaviour, IMouseHoverSample
    {
        /// <summary>
        ///  交点
        /// </summary>
        [SerializeField]
#if ODIN_INSPECTOR
        [LabelText("交点")]
#endif
        private RectTransform intersectionPoint;

        /// <summary>
        ///  鼠标悬浮状态改变时调用
        /// </summary>
        public void OnHoverStateChanged(bool newHoverState)
        {
            if (intersectionPoint) intersectionPoint.gameObject.SetActive(newHoverState);
        }

        /// <summary>
        ///  鼠标悬浮时，每帧采样数据调用
        /// </summary>
        public void OnSample(LineVertexInfo sample)
        {
            if (intersectionPoint == null) return;
            
            // 设置交点位置，将UV坐标的y值映射到0~Height设置给AnchoredPosition.y即可
            var v = sample.UV.y;
            var height = v * sample.BoundaryHandler.Height;
            intersectionPoint.anchoredPosition = new Vector2(0, height - intersectionPoint.sizeDelta.y / 2);
        }

        private void OnValidate()
        {
            var rectChildren = GetComponentsInChildren<RectTransform>(true);
            intersectionPoint = rectChildren.FirstOrDefault(i => i.name == "交点");

            var rectTransform = intersectionPoint?.GetComponent<RectTransform>();
            if (rectTransform)
            {
                rectTransform.anchorMin = new Vector2(0.5f, 0);
                rectTransform.anchorMax = new Vector2(0.5f, 0);
                rectTransform.pivot = new Vector2(0.5f, 0);
                rectTransform.anchoredPosition = new Vector2(0, 0);
            }
        }
    }
}